package com.lw.leetcode.arr.a;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * 6141. 合并相似的物品
 *
 * @author liw
 * @version 1.0
 * @date 2022/8/7 20:43
 */
public class MergeSimilarItems {

    public List<List<Integer>> mergeSimilarItems(int[][] items1, int[][] items2) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int[] ints : items1) {
            map.put(ints[0], ints[1]);
        }
        List<List<Integer>> list = new ArrayList<>();
        for (int[] ints : items2) {
            int anInt = ints[0];
            Integer v = map.get(anInt);
            if (v == null) {
                list.add(Arrays.asList(anInt, ints[1]));
            } else {
                list.add(Arrays.asList(anInt, v + ints[1]));
                map.put(anInt, -1);
            }
        }
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() != -1) {
                list.add(Arrays.asList(entry.getKey(), entry.getValue()));
            }
        }
        Collections.sort(list, (a, b) -> Integer.compare(a.get(0), b.get(0)));
        return list;
    }

}
